import { BeSwitch } from '../../../../model/parts/BeSwitch';
import { PartSlaver } from '../../../../model/parts/PartBase';
import { AppModel } from '../../../../model/AppModel';
import { createPartMenu, createUIWidgetMenu } from '../BlockPackage'

export default {

    category: Blockly.Categories.event ,
    
    color: [
        Blockly.Colours.bepart.primary,
        Blockly.Colours.bepart.secondary,
        Blockly.Colours.bepart.tertiary
    ] ,

    previousStatement: false ,
    nextStatement: true ,
    hat: true ,
    
    eventHandle: true ,

    init(model: AppModel) {
        this.appendDummyInput()
                .appendField("当开关")
                .appendField(createPartMenu(model, BeSwitch), 'switch')
                .appendField(new Blockly.FieldDropdown(() => {
                    return [
                        ['ON' , 'on'] ,
                        ['OFF' , 'off'] ,
                        ['Both' , 'both'] ,
                    ]
                }), 'event')
    } ,

    coder: {
        JavaScript(block: any, coder: any, model: AppModel) {
            
            // 
            let partUUID = block.getFieldValue('switch')
            let part: PartSlaver = model.findPartFromUUID(partUUID)
            if(!part)
                return "// unknow LED part uuid: " + partUUID

            // let val = coder.valueToCode(block, 'switch', coder.ORDER_ASSIGNMENT) || '0'
            let event = block.getFieldValue('event')

            
            let inner = ''
            let nextBlock = block.nextConnection && block.nextConnection.targetBlock()
            if(nextBlock) {
                coder.indent ++
                inner = coder.blockToCode(nextBlock)
                coder.indent --
            }

            return `${coder.indentString()}${part.remoteVar()}.on( "${event}", async ()=>{
${inner}
${coder.indentString()}})\n`
        }
    }
}
